import pymysql
from dbutils.pooled_db import PooledDB
import threading

''' 通过类实现单例模式 '''

dbPoolInfo = threading.local()

class db(object):
    def __init__(self):
        self.pool = PooledDB(
            creator=pymysql,  # 使用链接数据库模块
            maxconnections=6,  # 连接池允许的最大连接数
            mincached=2,  # 初始化的链接数
            host='127.0.0.1',
            blocking=True,  # 没有可用链接则阻塞等待
            ping=0,  # 拿到链接后,ping MySQL服务是否可用. 0:不ping
            port=3306,
            user='root',
            password='123456',
            database='my_blog',
            charset='utf8'
        )

    def open(self):
        conn = self.pool.connection()
        cursor = conn.cursor()
        return conn, cursor

    def close(self, conn, cursor):
        print(self)
        cursor.close()
        conn.close()

    def fetchall(self, sql, *args):
        with db() as cursor:
            cursor.execute(sql, args)
            # result = cursor.fetchall()
            result = cursor.fetchmany(2)

        # '''获取所有数据'''
        # conn, cursor = self.open()
        # cursor.execute(sql, args)
        # result = cursor.fetchall()
        # self.close(conn, cursor)

        return result

    def fetchone(self, sql, *args):
        ''' 获取单条数据 '''
        with db() as cursor:
            cursor.execute(sql, args)
            result = cursor.fetchone()


        # conn, cursor = self.open()
        # cursor.execute(sql, args)
        # result = cursor.fetchone()
        # self.close(conn, cursor)

        return result

    def __enter__(self):
        conn, cursor = self.open()
        dbPoolInfo.conn = conn
        dbPoolInfo.cursor = cursor
        return cursor
    def __exit__(self, exc_type, exc_val, exc_tb):
        conn = dbPoolInfo.conn
        cursor = dbPoolInfo.cursor
        conn.close
        cursor.close
